/**
 * 如果运行时报错找不到 pngjs，请在 scripts/文件夹下执行 npm install
 */
import { PNG } from 'pngjs';
import * as stream from 'stream';


type ImageData = {

    width: number

    height: number,

    data: Buffer
}


type ModifyData = {

    originImageData: ImageData;

    pngFile: string;

    pngBuffer: Buffer

}


/**
 * 检查 PNG 图片中是否每一个像素的 Alpha 通道是否都是 255，如果是的话，这张图片应该以 JPG 的形式进行存储
 */
export class CheckPngWithoutAlpha implements plugins.Command {



    private modifyList: ModifyData[] = [];

    constructor() {
    }

    async onFile(file: plugins.File) {
        if (file.extname == ".png") {
            const needModify = await readPNG(file);
            if (needModify) {
                this.modifyList.push(needModify);
            }
        }
        return file;

    }

    async onFinish(commandContext: plugins.CommandContext) {

        for (let item of this.modifyList) {
            var jpeg = require('jpeg-js');
            var jpegImageData = jpeg.encode(item.originImageData, 80);
            const basename = item.pngFile.split("/").join("_").replace(".png", "");
            commandContext.createFile(`test/${basename}.jpg`, jpegImageData.data);
            commandContext.createFile(`test/${basename}.png`, item.pngBuffer);
        }
    }
}


function readPNG(file: plugins.File) {

    return new Promise<ModifyData | null>((reslove, reject) => {

        // 创建一个bufferstream
        const pngStream = new stream.PassThrough();
        //将Buffer写入
        pngStream.end(file.contents);
        pngStream.pipe(new PNG({
            filterType: 4
        })).on('parsed', function () {
            const imageData: ImageData = this;
            let hasAlpha = false;
            for (let y = 0; y < imageData.height; y++) {
                for (let x = 0; x < imageData.width; x++) {
                    const idx = (imageData.width * y + x) << 2;
                    const alpha = imageData.data[idx + 3];
                    if (alpha < 255) {
                        hasAlpha = true;
                        break;
                    }
                }
            }

            if (!hasAlpha) {
                console.log(`${file.origin} 无透明区域，应修改为 JPG 图片 `)
                reslove({ originImageData: imageData, pngBuffer: file.contents, pngFile: file.origin });
            }
            else {
                reslove(null)
            }

        });
    })

}